(function($){
	
	$(document).ready(function(){
		
		var show = $.cookie("dislaycart");

		// Add event trigger for showing cart summary on button click
		var show_cart_btn = $("#show_cart_btn");
		show_cart_btn.on("click", function( e ){ 
			if(cart_view.is(":visible"))
				$(window).trigger("hide_cart");
			else
				$(window).trigger("show_cart");
		});
		
		$("#hide_btn").on("click", function( e ){ 
			$(window).trigger("hide_cart");
		});

		// Listener for showing cart
		$(window).bind("show_cart", function( e ){

			// Get latest cart object from server
			$.ajax("/ajax/get_cart",{
				dataType : "json",
				success : function( data, xhr){ 
					/*
					data.items = object of items,
					data.count = int (items)
					data.totalprice = int (price)
					*/

					if(data.count > 0) {
						render_cart(data.items); 
					} else {
						minicart.hide(function(e){$(this).remove();});
					}
				},
				error : function( err, xhr ){ console.error(err);}
			});
		});

		// Listener for hiding cart
		$(window).bind("hide_cart", function( e ){

			show_cart_btn.html("Visa");
			cart_view.fadeOut(100);
		});

		// Cart change listener for when products are added / removed to cart
		$(window).bind("cart_change", function( e ){
			// Update the cart preview row
			$.ajax("/ajax/get_cart_summary",{
				dataType : "json",
				success : function( data, xhr){ render_mini_cart(data); },
				error : function( err, xhr ){ console.error(err);}
			});
		});
		
		var table_body = $("#summary_table tbody");
		var cart_view = $(".cart_view")

		function render_cart( data ){

			table_body.empty();

			var total_price = 0;
			var total_count = 0;

			for(var i in data){

				var item = data[i];
				var row = $("<tr>").attr("id", item.id);
				var cells = [$("<td>"),$("<td>"),$("<td>"),$("<td>")];
				var removebtn = $("<span class='del_icon'></span>").data('pid', data.id);
				var prodlink = $("<a href='"+productLink(item)+"'>"+item.name+"</a>");

				cells[0].append( prodlink );
				cells[1].html( item.qty );
				cells[2].html( item.price +" kr");
				cells[3].append( removebtn );

				table_body.append(row.append(
					cells[0],
					cells[1],
					cells[2],
					cells[3]
					));

				total_price += (parseInt(item.qty) * parseInt(item.price));
				total_count += parseInt(item.qty);
			}

			// Add summary row
			var row = $("<tr class='totality'>");
			var cells = [$("<td>"),$("<td>"),$("<td>"),$("<td>")];
			var clearbtn = $("<span class='clear_icon'></span>");

			cells[0].html("Summa :");
			cells[1].html( total_count+" st");
			cells[2].html( total_price+" kr");
			cells[3].append( clearbtn );

			table_body.append(row.append(
				cells[0],
				cells[1],
				cells[2],
				cells[3]
				));

			// Apply listeners
			table_body.find('.del_icon').each(function( ix, it ){
				$(it)
				.attr("title", "Ta bort produkt")
				.on("click", function(){
					var id = $(this).closest("tr").attr("id");
					id = parseInt(id.split("_")[1]);
					removeProduct( id );	
				});

			});

			// Change label on controller btn
			show_cart_btn.html("Dölj");

			cart_view.fadeIn(100);
		}

		function productLink(itm){
			return "/produkt/"+itm.id.split("_")[1];
		}


		function removeProduct(id){
			$.ajax("/ajax/set_item/"+id+"/0", {
				dataType : "json",
				success : function( data ){
					if(data.status === true){
						var strid = "prod_"+id;
						$(".cart_view").find("#"+strid).hide(function(){ 
							$(this).remove(); 
							$(window).trigger("show_cart");
						});
					}
				},
				error : function( errro ){
					console.log(error);
				}
			});
		}
		
		var minicart = $(".cart_preview");
		var minicart_count = $("#cart_summary_count");
		var minicart_price = $("#cart_summary_price");

		function render_mini_cart( data ){

			minicart_count.html( data.count );
			minicart_price.html( data.price );

			// Show cart summary
			if( ! minicart.is(":visible") ) {
				minicart
				.removeClass("hide")
				.fadeIn("show", 500);
			}
			else{
				
			}
		}
	});
})(jQuery);